<?php

/**
 * Class VerifyService
 */
include_once("./resource/SDK/CCPRestSmsSDK.php");
class VerifyService extends BaseService
{

    private static $self           =   NULL;
    private $mUser                  =   NULL;
    private $mUserFund              =   NULL;
    private $mInviteCode            =   NULL;
    private $mUserAward             =   NULL;
    private $mUserTicket            =   NULL;




    static public function instance()
    {
        if (self::$self == NULL) {
            self::$self = new self;
        }
        return self::$self;
    }


    public function __construct()
    {

        $this->mUser               =   new Involved_UserModel();
        $this->mUserFund           =   new Involved_UserFundModel();
        $this->mInviteCode         =   new Involved_InviteCodeModel();
        $this->mUserAward          =   new Involved_UserAwardModel();
        $this->mUserTicket         =   new Involved_UserTicketModel();
    }


    /**
     * 修改可用红包改为过期
     * @param $user_id
     */
    public function UserTicketRed($user_id)
    {
        $ticket = $this->mUserTicket->MyUserTicket($user_id);
        $aData = [
            'status' => 'PAST_DUE'
        ];
        foreach($ticket as $k=>$v){
             $this->mUserTicket->update($aData,['auto_id'=>$v->auto_id]);
        }
        $red = $this->mUserAward->MyUserRed($user_id);
        foreach($red as $k=>$v){
            $this->mUserAward->update($aData,['auto_id'=>$v->auto_id]);
        }
    }


    /**
     * 注册信息验证
     * @param $paramObj
     * @throws Exception
     */
    public function VerifyRegister($paramObj)
    {
        #参数验证
        if(empty($paramObj->mobile) || empty($paramObj->pwd) || empty($paramObj->captcha)){
            throw new Exception('必填项不能为空', ProfessionErrorCodeEnum::STATUS_ERROR_PARAMS_MUST);
        }

        #手机号验证
        if (!preg_match('/^1[34578]\d{9}$/', $paramObj->mobile)) {
            throw new Exception("手机号码错误", ProfessionErrorCodeEnum::ERROR_USER_MOBILE_FAILURE);
        }

        #手机号是否已注册
        $mobile = $this->mUser->JsCheckMobile($paramObj->mobile);
        if ($mobile) {
            throw new Exception("手机号已注册", ProfessionErrorCodeEnum::ERROR_ACCOUNT_EXIST);
        }

        #判断短信验证
        $info =session_get(UserEnum::CLIENT_NEWS_CAPTCHA);
        if ($info['news_captcha']!=$paramObj->captcha) {
            throw new Exception("短信验证码有误", ProfessionErrorCodeEnum::ERROR_ACCOUNT_EXIST);
        }

        #邀请人验证码验证
        if(!empty($paramObj->invite_phone)){
            $invite_phone = $this->mUser->JsCheckCode($paramObj->invite_phone);
            if(!$invite_phone){
                throw new Exception("邀请人验证码不存在", ProfessionErrorCodeEnum::ERROR_ACCOUNT_EXIST);
            }
        }
        $invite_code = $this->mInviteCode->insert(['invite_code'=>1]);

        $salt  =  rand(100000, 999999);
        #注册用户
        $aData = [
            'user_name'          =>     'GPW'.time(),
            'telephone'          =>     $paramObj->mobile,
            'password'           =>     UserEnum::get(md5(md5($paramObj->pwd)),$salt),
            'salt'               =>     $salt,
            'invite_code'        =>     $invite_code,
            'add_time'           =>     time(),
        ];

        $user_id = $this->mUser->insert($aData);

        if($user_id){
            //注册送红包
//                DB::table('user_award')->insert(array(
//                    array('user_id' => $user_id, 'amount' =>'1800','restrict_amount'=>'100000','road'=>'REGISTER','status'=>'AVAILABLE','add_time'=>time(),'due_time'=>time()+86400*15),
//                    array('user_id' => $user_id, 'amount' =>'3800','restrict_amount'=>'500000','road'=>'REGISTER','status'=>'AVAILABLE','add_time'=>time(),'due_time'=>time()+86400*15),
//                    array('user_id' => $user_id, 'amount' =>'6600','restrict_amount'=>'1000000','road'=>'REGISTER','status'=>'AVAILABLE','add_time'=>time(),'due_time'=>time()+86400*15),
//                    array('user_id' => $user_id, 'amount' =>'19800','restrict_amount'=>'3000000','road'=>'REGISTER','status'=>'AVAILABLE','add_time'=>time(),'due_time'=>time()+86400*15),
//                    array('user_id' => $user_id, 'amount' =>'29800','restrict_amount'=>'5000000','road'=>'REGISTER','status'=>'AVAILABLE','add_time'=>time(),'due_time'=>time()+86400*15),
//                ));
            //注册送体验金
                DB::table('exper_amount')->insert(array(
                    array('user_id' => $user_id, 'amount' =>'666600','road'=>'REGISTER','status'=>'AVAILABLE','add_time'=>time(),'due_time'=>time()+86400*15),
                ));
            //注册送加息券
                DB::table('user_ticket')->insert(array(
                    array('user_id' => $user_id, 'rate' => '100', 'restrict_item' => 'ALL', 'road' => 'REGISTER', 'status' => 'AVAILABLE', 'add_time' => time(), 'due_time' => time() + 86400 * 15),
                ));
            $this->mUserFund->insert(['user_id' => $user_id]);
            UserService::instance()->run($user_id);
            UserService::instance()->send(
            // 接收者ID
                $user_id,
                // 标题
                '恭喜您注册成功',
                // 内容
                '尊敬的用户，您已成功注册钢票网。6666元体验金和618元新手红包已送达您的账户，详情见“我的奖励”。
'
            );

            SMSService::instance()->RegisterSMS('618','6666','1',$paramObj->mobile);
            //邀请人
            if(!empty($paramObj->invite_phone)){
                $invite_id = $this->mUser->CheckInviteId($paramObj->invite_phone);
                if($invite_id){
                    DB::table('user')->where('user_id',$user_id)->update(array('parent_id' => $invite_id->user_id));
                    DB::table('invite')->insert(array(
                        array('user_id' => $user_id, 'invite_id' =>$invite_id->user_id,'add_time'=>time()),
                    ));
                }
            }

            $data=$this->mUser->UserFirphone($paramObj->mobile);
            #存储SESSION
            Session::put(UserEnum::USER_INFO_USER_ID, $user_id);
            Session::put(UserEnum::USER_INFO_SESSION_KEY, $data);

        }else{
            throw new Exception('注册失败');
        }

    }

    /**
     * 注册手机号js验证
     * @param $mobile
     * @return mixed
     */
    public function JsCheckMobile($mobile)
    {
        return $this->mUser->JsCheckMobile($mobile);
    }

    /**
     * 注册验证码验证
     * @param $code
     * @return mixed
     */
    public function JsCheckCode($code){
        return $this->mUser->JsCheckCode($code);
    }
    /**
     * 注册短信验证
     * @param $paramObj
     * @return int
     */
    public function JsCheckNewsCaptcha($paramObj)
    {
        $info =session_get(UserEnum::CLIENT_NEWS_CAPTCHA);
        $time =time()-$info['time'];
        if($info['news_captcha'] == $paramObj->news_captcha && $info['mobile'] == $paramObj->mobile){
            if($time<=600){
                return 1;
            }else{
                return 2;
            }
        }else{
            return  3;
        }
    }

    /**
     * 注册获取短信验证码
     * @param $paramObj
     * @return int
     */
    public function GetNewsCaptcha($paramObj)
    {
        $info =session_get(UserEnum::CLIENT_NEWS_CAPTCHA);
        $time = 60-(time()-$info['time']);
        if(time()-$info['time']<=60&&$paramObj->mobile==$info['mobile']) {
            return $time;
        }
        $news_captcha = substr(str_shuffle("012345678901234567890123456789"), 0, 6);
        $data = SMSService::instance()->SendSMS($paramObj->mobile,$news_captcha);
        if($data['code']==0){
            $aData["mobile"] = $paramObj->mobile;
            $aData['time'] = time();
            $aData['news_captcha'] = $news_captcha;
            Session::put(UserEnum::CLIENT_NEWS_CAPTCHA,$aData);
        }
        return $data;
    }

    /**
     * 发送短信验证
     * @param $to
     * @param $datas
     * @param $tempId
     * @return int
     */
    function sendTemplateSMS($to,$datas,$tempId)
    {

        // 初始化REST SDK
        global $accountSid,$accountToken,$appId,$serverIP,$serverPort,$softVersion;

        $accountSid= '8a48b551544cd73f0154893f6f383aaf';
        $accountToken= 'c8a7e905a48c4ceab3613ef27bae589d';
        $appId='8a216da8555d110e01555d3ca0d201ef';
        $serverIP='app.cloopen.com';
        $serverPort='8883';
        $softVersion='2013-12-26';

        $rest = new REST($serverIP,$serverPort,$softVersion);
        $rest->setAccount($accountSid,$accountToken);
        $rest->setAppId($appId);
        // 发送模板短信
        //echo "Sending TemplateSMS to $to <br/>";
        $result = $rest->sendTemplateSMS($to,$datas,$tempId);
        if($result == NULL ) {
            echo "result error!";
            die;
        }
        if($result->statusCode!=0) {
//            echo "error code :" . $result->statusCode . "<br>";
//            echo "error msg :" . $result->statusMsg . "<br>";
//            return $result->statusCode;
            return $result->statusCode;
            //TODO 添加错误处理逻辑
        }else{
//            echo "Sendind TemplateSMS success!<br/>";
//            // 获取返回信息
//            $smsmessage = $result->TemplateSMS;
//            echo "dateCreated:".$smsmessage->dateCreated."<br/>";
//            echo "smsMessageSid:".$smsmessage->smsMessageSid."<br/>";
//            //TODO 添加成功处理逻辑
            return 10000;
        }
    }


    /**
     * Web注册信息验证
     * @param $paramObj
     * @throws Exception
     */
    public function WebVerifyRegister($paramObj)
    {
        #参数验证
        if(empty($paramObj->mobile) || empty($paramObj->pwd) || empty($paramObj->captcha)){
            throw new Exception('必填项不能为空', ProfessionErrorCodeEnum::STATUS_ERROR_PARAMS_MUST);
        }

        #手机号验证
        if (!preg_match('/^1[34578]\d{9}$/', $paramObj->mobile)) {
            throw new Exception("手机号码错误", ProfessionErrorCodeEnum::ERROR_USER_MOBILE_FAILURE);
        }

        #手机号是否已注册
        $mobile = $this->mUser->JsCheckMobile($paramObj->mobile);
        if ($mobile) {
            throw new Exception("手机号已注册", ProfessionErrorCodeEnum::ERROR_ACCOUNT_EXIST);
        }

        #判断短信验证
//        $info =session_get(UserEnum::CLIENT_NEWS_CAPTCHA);
//        if ($info['news_captcha']!=$paramObj->captcha) {
//            throw new Exception("短信验证码有误", ProfessionErrorCodeEnum::ERROR_ACCOUNT_EXIST);
//        }

        #邀请人验证码验证
        if(!empty($paramObj->invite_phone)){
            $invite_phone = $this->mUser->JsCheckCode($paramObj->invite_phone);
            if(!$invite_phone){
                throw new Exception("邀请人验证码不存在", ProfessionErrorCodeEnum::ERROR_ACCOUNT_EXIST);
            }
        }
        $invite_code = $this->mInviteCode->insert(['invite_code'=>1]);

        $salt  =  rand(100000, 999999);
        #注册用户
        $aData = [
            'user_name'          =>     'GPW'.time(),
            'telephone'          =>     $paramObj->mobile,
            'password'           =>     UserEnum::get(md5(md5($paramObj->pwd)),$salt),
            'salt'               =>     $salt,
            'invite_code'        =>     $invite_code,
            'add_time'           =>     time(),
        ];

        $user_id = $this->mUser->insert($aData);

        if($user_id){
            //注册送红包
//                DB::table('user_award')->insert(array(
//                    array('user_id' => $user_id, 'amount' =>'1800','restrict_amount'=>'100000','road'=>'REGISTER','status'=>'AVAILABLE','add_time'=>time(),'due_time'=>time()+86400*15),
//                    array('user_id' => $user_id, 'amount' =>'3800','restrict_amount'=>'500000','road'=>'REGISTER','status'=>'AVAILABLE','add_time'=>time(),'due_time'=>time()+86400*15),
//                    array('user_id' => $user_id, 'amount' =>'6600','restrict_amount'=>'1000000','road'=>'REGISTER','status'=>'AVAILABLE','add_time'=>time(),'due_time'=>time()+86400*15),
//                    array('user_id' => $user_id, 'amount' =>'19800','restrict_amount'=>'3000000','road'=>'REGISTER','status'=>'AVAILABLE','add_time'=>time(),'due_time'=>time()+86400*15),
//                    array('user_id' => $user_id, 'amount' =>'29800','restrict_amount'=>'5000000','road'=>'REGISTER','status'=>'AVAILABLE','add_time'=>time(),'due_time'=>time()+86400*15),
//                ));
            //注册送体验金
            DB::table('exper_amount')->insert(array(
                array('user_id' => $user_id, 'amount' =>'666600','road'=>'REGISTER','status'=>'AVAILABLE','add_time'=>time(),'due_time'=>time()+86400*15),
            ));
            //注册送加息券
            DB::table('user_ticket')->insert(array(
                array('user_id' => $user_id, 'rate' => '100', 'restrict_item' => 'ALL', 'road' => 'REGISTER', 'status' => 'AVAILABLE', 'add_time' => time(), 'due_time' => time() + 86400 * 15),
            ));
            $this->mUserFund->insert(['user_id' => $user_id]);
            UserService::instance()->run($user_id);
            UserService::instance()->send(
            // 接收者ID
                $user_id,
                // 标题
                '恭喜您注册成功',
                // 内容
                '尊敬的用户，您已成功注册钢票网。6666元体验金和618元新手红包已送达您的账户，详情见“我的奖励”。
'
            );

            SMSService::instance()->RegisterSMS('618','6666','1',$paramObj->mobile);
            //邀请人
            if(!empty($paramObj->invite_phone)){
                $invite_id = $this->mUser->CheckInviteId($paramObj->invite_phone);
                if($invite_id){
                    DB::table('user')->where('user_id',$user_id)->update(array('parent_id' => $invite_id->user_id));
                    DB::table('invite')->insert(array(
                        array('user_id' => $user_id, 'invite_id' =>$invite_id->user_id,'add_time'=>time()),
                    ));
                }
            }

            $data=$this->mUser->UserFirphone($paramObj->mobile);
            #存储SESSION
            Session::put(UserEnum::USER_INFO_USER_ID, $user_id);
            Session::put(UserEnum::USER_INFO_SESSION_KEY, $data);

        }else{
            throw new Exception('注册失败');
        }

    }

    /**
     * 数据加密
     * time:2016.05.17
     */
    public function UserMoneyjiami($input){
        $size = mcrypt_get_block_size ( MCRYPT_3DES, 'ecb' );
        $input =$this->pkcs5_pad($input, $size);
        $key = str_pad ( 'AQWSEDRFTGYHUJIKOLPXCVBN', 24, '0' );
        $td = mcrypt_module_open ( MCRYPT_3DES, '', 'ecb', '' );
        $iv = @mcrypt_create_iv ( mcrypt_enc_get_iv_size ( $td ), MCRYPT_RAND );
        @mcrypt_generic_init ( $td, $key, $iv );
        $data = mcrypt_generic ( $td, $input );
        mcrypt_generic_deinit ( $td );
        mcrypt_module_close ( $td );
        $data = base64_encode ( $data );
        $data = str_replace('+','&',$data);
        return $data;

    }

    public   function pkcs5_pad($text, $blocksize) {
        $pad = $blocksize - (strlen ( $text ) % $blocksize);
        return $text . str_repeat ( chr ( $pad ), $pad );
    }
    /**
     * 数据解密
     * time:2016.05.17
     */
    public   function pkcs5_unpad($text) {
        $pad = ord ( $text {strlen ( $text ) - 1} );
        //return $pad;
        if ($pad > strlen ( $text )) {
            return false;
        }
        if (strspn ( $text, chr ( $pad ), strlen ( $text ) - $pad ) != $pad) {
            return false;
        }
        return substr ( $text, 0, - 1 * $pad );
    }
    public  function UserMoneyjiamis($encrypted){
        $encrypted = str_replace('&','+',$encrypted);
        $encrypted = base64_decode ( $encrypted );
        //return $encrypted;
        $key = str_pad ( 'AQWSEDRFTGYHUJIKOLPXCVBN', 24, '0' );
        $td = mcrypt_module_open ( MCRYPT_3DES, '', 'ecb', '' );
        $iv = @mcrypt_create_iv ( mcrypt_enc_get_iv_size ( $td ), MCRYPT_RAND );
        $ks = mcrypt_enc_get_key_size ( $td );
        @mcrypt_generic_init ( $td, $key, $iv );
        $decrypted = mdecrypt_generic ( $td, $encrypted );
        mcrypt_generic_deinit ( $td );
        mcrypt_module_close ( $td );
        $y=$this->pkcs5_unpad( $decrypted );
        return $y;
    }

}


